package top.smallway.lightbandassistant_app.network;

import android.content.Context;

import com.alibaba.fastjson2.JSONObject;
import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginManager {
    private OkHttpClient httpClient;
    private final ClearableCookieJar cookieJar;
    private boolean isLoggedIn = false;
    public String ID;


    public void setID(String ID) {
        this.ID = ID;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String username;

    public String getID() {
        return ID;
    }

    public String getUsername() {
        return username;
    }

    public ClearableCookieJar getCookieJar() {
        return cookieJar;
    }

    public String GetToken() {
        httpClient = new OkHttpClient.Builder().cookieJar(cookieJar).build();
        Request request = new Request.Builder().url("https://bs.smallway.top/gettoken/").get().build();
        try {
            Response response = httpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public LoginManager(Context context) {
        cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
        httpClient = new OkHttpClient.Builder().cookieJar(cookieJar).build();
    }

    public boolean login(String username, String password, final LoginStatus loginStatus) {
        // 构建登录请求
        RequestBody requestBody = new FormBody.Builder().add("username", username).add("password", password).build();

        Request request = new Request.Builder().url("https://bs.smallway.top/login/").addHeader("X-CSRFToken", GetToken()).post(requestBody).build();

        try {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body().string());
                loginStatus.Logined(jsonObject.getString("username"), jsonObject.getString("id"), jsonObject.getString("email"));
                setID(jsonObject.getString("id"));
                setUsername(jsonObject.getString("username"));
                isLoggedIn = true;
                return true;
            }
        } catch (IOException e) {
            loginStatus.Unlogined();
            e.printStackTrace();
        }

        return false;
    }

    public void register(String username, String password, String email, final RegStatus regStatus) {
        // 构建注册请求
        RequestBody requestBody = new FormBody.Builder().add("username", username).add("password", password).add("email", email).build();

        Request request = new Request.Builder().url("https://bs.smallway.top/register/").addHeader("X-CSRFToken", GetToken()).post(requestBody).build();
        Response response = null;
        try {
            response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                regStatus.RegSuccess();
            } else {
                regStatus.RegFailed(response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
            regStatus.RegFailed(500); // 处理请求失败的情况
        } finally {
            if (response != null) {
                response.close(); // 关闭响应体
            }
        }

    }

    public boolean logout() {
        // 清除cookie，模拟登出
        cookieJar.clear();
        setID("");
        setUsername("");
        isLoggedIn = false;
        return true;
    }

    public boolean isLoggedIn() {
        return isLoggedIn;
    }


    /**
     * 使用COOKIE尝试登录，回调接口处理登录
     *
     * @param loginStatus
     * @return
     */
    public boolean checkLoggedIn(final LoginStatus loginStatus) {
        Request request = new Request.Builder().url("https://bs.smallway.top/login/").get().build();
        try {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body().string());
                loginStatus.Logined(jsonObject.getString("username"), jsonObject.getString("id"), jsonObject.getString("email"));  //回调登陆成功
                setID(jsonObject.getString("id"));
                setUsername(jsonObject.getString("username"));
                isLoggedIn = true;
                return true;
            }
        } catch (IOException e) {
            loginStatus.Unlogined();  //回调登陆失败
            e.printStackTrace();
        }
        loginStatus.Unlogined();  //回调登陆失败
        return false;
    }



    public interface LoginStatus {
        void Logined(String username, String id, String email);

        void Unlogined();
    }

    public interface RegStatus {
        void RegSuccess();

        void RegFailed(int code);
    }
}
